package com.mayikt.member.service.impl;


import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.bean.MeiteBeanUtils;
import com.mayikt.constants.Constants;
import com.mayikt.generator.TokenGenerator;
import com.mayikt.member.entity.UserDo;
import com.mayikt.member.mapper.UserMapper;
import com.mayikt.member.output.dto.UserOutDTO;
import com.mayikt.member.service.MemberService;
import com.mayikt.type.TypeCastHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: CHEN JIN LONG
 * @Date: 2019/1/12 00:36
 * @Description:
 */
@RestController
public class MemberServiceImpl extends BaseApiService<UserOutDTO> implements MemberService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenGenerator tokenGenerator;


    @Override
    public BaseResponse<UserOutDTO> existMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return setResultError("手机号不能为空");
        }

        UserDo userDo = userMapper.existMobile(mobile);
        if (userDo == null) {
            return setResultError(Constants.EXISTMOBILE_CODE_203, "用户信息不存在");
        }
        return setResultSuccess(MeiteBeanUtils.doToDto(userDo, UserOutDTO.class));
    }

    @Override
    public BaseResponse<UserOutDTO> getInfo(String token) {
        //1.验证参数
        if (StringUtils.isEmpty(token))
            return setResultError("token不能为空");
        //2.使用token查询redis中的userId
        String redisUserId = tokenGenerator.getToken(token);
        if (StringUtils.isEmpty(redisUserId))
            setResultError("token错误或已失效");
        //3.使用userId查询用户信息
        Long userId = TypeCastHelper.toLong(redisUserId);
        UserDo userDo = userMapper.findByUserId(userId);
        if (userDo == null)
            return setResultError("用户不存在");

        //用户账号状态
        //下节课将转换代码重构
        //假设token存放在PC端口，在cookie里
        //android IOS 存放在本地文件中
        //当前的token存在哪些问题？

        //用户退出或者修改密码的情况下，应该把之前的token清空
        //token如果防止伪造？真正很难防御的，只能通过本人操作验证尽量实现别人在安全体系上，xss js获取cookie
        //操作短信验证码
        return setResultSuccess(MeiteBeanUtils.doToDto(userDo, UserOutDTO.class));
    }
}
